package blog.web.utils;

import blog.sys.entity.SysFile;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pub.functions.FsFuncs;
import pub.web.ServletUtils;
import blog.sys.service.SysFileService;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * Created by zzl on 2015/12/30.
 */
@Component
public class SysFileUtils {

    public static String replacePlaceholderToUrl(String html) {
        if(html == null) {
            return null;
        }
        HttpServletRequest request = ServletUtils.getRequest();
        String requestUrl = request.getRequestURL().toString();
        int pos = requestUrl.indexOf('/', 10);
        String server = requestUrl.substring(0, pos);

        String home = request.getContextPath();
        String fileUrl = server + home + "/file/get.do?id=";

        String prolog = "@(FILE-ID=";

        StringBuilder sbHtml = new StringBuilder();
        pos = 0;
        while(true) {
            int pos1 = html.indexOf(prolog, pos);
            if(pos1 == -1) {
                sbHtml.append(html.substring(pos));
                break;
            }
            int pos2 = html.indexOf(')', pos1);
            String fileId = html.substring(pos1 + prolog.length(), pos2);
            sbHtml.append(html.substring(pos, pos1));
            sbHtml.append(fileUrl + fileId);
            pos = pos2 + 1;
        }
        String html2 = sbHtml.toString();
        return html2;
    }


    public String getFsPath(Integer id) {
        String sysFileDir = servletContext.getRealPath("/sysfile");
        String SEP = File.separator;
        //
        File fileDir = new File(sysFileDir + SEP + id);
        String[] fileNames = fileDir.list();
        String fileName;
        if (fileNames == null || fileNames.length == 0) {
            fileDir.mkdirs();
            SysFile sysFile = sysFileService.get(id);
            if (sysFile == null) {
                return null;
            }
            fileName = FsFuncs.getFileName(sysFile.getName());

            String localFileName = "file";
            int lastDotPos = fileName.lastIndexOf('.');
            if (lastDotPos != -1) {
                localFileName += fileName.substring(lastDotPos);
            }
            //
            fileName = localFileName;

            try {
                File file = new File(fileDir.getAbsolutePath() + SEP + fileName);
                OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
                os.write(sysFile.getContent());
                os.close();
            }
            catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            fileName = fileNames[0];
        }

        String filePath = new File(fileDir, fileName).getAbsolutePath();
        return filePath;
    }

    public String getBase64Content(Integer id) throws Exception {
        String filePath = getFsPath(id);
        return getBase64Content(filePath);
    }

    public static String getBase64Content(String filePath) throws Exception {

        byte[] bts = FileUtils.readFileToByteArray(new File(filePath));
        java.util.Base64.Encoder encoder = java.util.Base64.getEncoder();
        String result = encoder.encodeToString(bts);
        return result;

//        FileInputStream fin = new FileInputStream(filePath);
//        ByteArrayOutputStream os = new ByteArrayOutputStream();
//        Base64OutputStream base64out = new Base64OutputStream(os, true);
//
//        byte[] buffer = new byte[4096];
//        int len = 0;
//        while ((len = fin.read(buffer)) >= 0) {
//            base64out.write(buffer, 0, len);
//        }
//
//        base64out.flush();
//        base64out.close();
//        String result = new String(os.toByteArray(), "UTF-8");
//        return result;
    }

//    public static void main(String[] args) throws Exception {
//        String xx = getBase64Content("T:/test1/DecisionTree.zip");
//        System.out.println(xx);
//    }

    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private ServletContext servletContext;

}
